<template>
  <div class="panel-header">
    <div class="panel-title">
      <i class="panel-icon speed-icon"></i>
      <span>设备实时速度趋势</span>
    </div>
    <div class="panel-controls">
      <!-- 右上角控制按钮 -->
      <el-button
        size="small"
        circle
        @click="updateChart"
        title="刷新数据"
      >
        <SvgIcon name="refresh" size="16" />
      </el-button>
    </div>
  </div>
  <div class="panel-body">
    <div ref="chartRef" class="chart-container"></div>
    <!-- 底部边距由ECharts配置和初始化时的尺寸设置提供 -->
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import { SvgIcon } from '@/components/icons'
import * as echarts from 'echarts'

const props = defineProps({
  equipmentList: {
    type: Array,
    default: () => []
  },
  initialSelectedEquipment: {
    type: String,
    default: ''
  }
})

const chartRef = ref(null)
const chart = ref(null)

// 监听设备列表变化
watch(() => props.equipmentList, () => {
  updateChart()
}, { deep: true })

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 获取容器的高度，并减去底部边距
  const containerHeight = chartRef.value.clientHeight;
  const containerWidth = chartRef.value.clientWidth;

  // 确保图表不会占用全部高度，留出底部边距
  const chartHeight = containerHeight - 10; // 留出10px的底部边距

  console.log('图表容器尺寸:', containerWidth, containerHeight);
  console.log('设置图表尺寸:', containerWidth, chartHeight);

  // 初始化图表时指定尺寸
  chart.value = echarts.init(chartRef.value);

  // 设置图表响应式
  const resizeHandler = () => {
    if (chart.value) {
      const newContainerHeight = chartRef.value.clientHeight;
      const newChartHeight = newContainerHeight - 10;
      chart.value.resize({
        width: 'auto',
        height: newChartHeight
      });
    }
  }
  window.addEventListener('resize', resizeHandler)

  // 组件卸载时移除事件监听
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler)
    chart.value && chart.value.dispose()
  })

  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chart.value) return
  updateAllDevicesChart()
}

// 更新所有设备的图表
const updateAllDevicesChart = () => {
  // 获取设备列表，如果为空则使用默认设备
  const devices = props.equipmentList.length > 0
    ? props.equipmentList
    : ['设备1', '设备2', '设备3', '设备4', '设备5']

  // 生成随机颜色
  const colors = [
    '#409EFF', // 蓝色
    '#67C23A', // 绿色
    '#E6A23C', // 黄色
    '#F56C6C', // 红色
    '#909399', // 灰色
    '#9B59B6', // 紫色
    '#3498DB', // 浅蓝色
    '#2ECC71', // 浅绿色
    '#F1C40F', // 浅黄色
    '#E74C3C'  // 浅红色
  ]

  // 生成时间点数据
  const now = new Date()
  const times = []
  for (let i = 0; i < 30; i++) {
    const time = new Date(now - (30 - i) * 1000 * 60)
    times.push(time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }))
  }

  // 为每个设备生成随机数据
  const seriesData = devices.map((device, index) => {
    // 生成随机数据
    const data = Array.from({ length: 30 }, () => Math.round(Math.random() * 150 + 50))

    return {
      name: device,
      type: 'line',
      stack: 'Total',
      smooth: true,
      symbol: 'none', // 不显示数据点标记
      lineStyle: {
        width: 2
      },
      areaStyle: {
        opacity: 0.5,
        color: colors[index % colors.length]
      },
      emphasis: {
        focus: 'series'
      },
      data: data
    }
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: devices,
      textStyle: {
        color: '#fff'
      },
      top: 10
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: 20, /* 使用固定像素值，确保底部有足够空间 */
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times,
      axisLabel: {
        color: '#fff',
        rotate: 45,
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      name: '速度 (米/分钟)',
      nameTextStyle: {
        color: '#fff'
      },
      min: 0,
      max: 250,
      interval: 50,
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    series: seriesData
  }

  chart.value.setOption(option)
}

// 没有其他处理函数

onMounted(() => {
  initChart()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  position: relative;
  box-sizing: border-box;
  padding-bottom: 10px; /* 确保容器底部有内边距 */
}
</style>
